package com.rich.datapump.biz.datasource

import com.mybatisflex.core.row.Db
import com.mybatisflex.core.util.StringUtil
import com.rich.datapump.biz.metadata.Column
import com.rich.datapump.biz.metadata.MetadataBean
import org.noear.solon.annotation.Component

abstract class CurrDSMapper {
    abstract fun getVersion(): String
    abstract fun getMetadatas(): List<MetadataBean>

    protected fun defaultMetadatasProcess(tableSql: String, colSql: String): List<MetadataBean> =
        Db.selectListBySql(tableSql).map { mdRow ->
            val md = mdRow.toEntity(MetadataBean::class.java)
            if (md.tableComment.isNullOrBlank())
                md.tableComment = "表${md.tableName}"
            md.nameHump = StringUtil.underlineToCamel(md.tableName)
            md.namePascal = StringUtil.firstCharToUpperCase(md.nameHump)
            md.columns =
                Db.selectListBySql(colSql, md.tableName)
                    .map { colRow ->
                        val col = colRow.toEntity(Column::class.java)
                        col.nameHump = StringUtil.underlineToCamel(col.columnName)
                        col.namePascal = StringUtil.firstCharToUpperCase(col.nameHump)
                        col
                    }
            md
        }
}

@Component
class MysqlDSMapper : CurrDSMapper() {
    override fun getVersion() =
        Db.selectOneBySql("select version()").toString()

    override fun getMetadatas(): List<MetadataBean> =
        super.defaultMetadatasProcess(
            "SELECT TABLE_NAME ,TABLE_COMMENT FROM INFORMATION_SCHEMA.`TABLES` WHERE table_schema = (SELECT DATABASE())",
            "SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT, IFNULL(CHARACTER_MAXIMUM_LENGTH,IFNULL(NUMERIC_PRECISION,DATETIME_PRECISION)) DATALENGTH FROM information_schema.COLUMNS WHERE table_schema = (SELECT DATABASE()) and table_name= ? ORDER BY ORDINAL_POSITION"
        )
}

@Component
class OracleDSMapper : CurrDSMapper() {
    override fun getVersion(): String =
        Db.selectOneBySql("select * from v\$version where rownum=1").toString()

    override fun getMetadatas(): List<MetadataBean> =
        super.defaultMetadatasProcess(
            "SELECT t.TABLE_NAME, tc.COMMENTS TABLE_COMMENT FROM USER_TABLES t,user_tab_comments tc WHERE t.TABLE_NAME = tc.TABLE_NAME",
            "SELECT  t.COLUMN_NAME, t.DATA_TYPE, c.COMMENTS COLUMN_COMMENT, t.DATA_LENGTH DATALENGTH FROM user_tab_columns t, user_col_comments c WHERE t.table_name = c.table_name AND t.COLUMN_NAME = c.COLUMN_NAME AND t.table_name = ?"
        )

}